﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using HostComputerPlatform.Models;
using HostComputerPlatform.ViewModels;
using ModuleBase;

namespace HostComputerPlatform.Services
{
    public class ExecutionFlowService : IExecutionFlowService
    {
        private bool _isRunning = false;
        private bool _isPaused = false;
        private int _currentIndex = 0;
        private List<(List<IModuleBase> modules, ObservableCollection<EditableItem> trueBranch, ObservableCollection<EditableItem> falseBranch)> _executionList;
        private CancellationTokenSource _cancellationTokenSource;

        public bool IsRunning => _isRunning;
        public bool IsPaused => _isPaused;

        public event Action StateChanged;

        public ExecutionFlowService(List<(List<IModuleBase> modules, ObservableCollection<EditableItem> trueBranch, ObservableCollection<EditableItem> falseBranch)> executionList)
        {
            _executionList = executionList;
        }

        public async Task ExecuteFlowAsync()
        {
            _isRunning = true;
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;

            while (_currentIndex < _executionList.Count && !token.IsCancellationRequested)
            {
                MyFunc.AddMessage($"开始执行步骤：{_currentIndex + 1}");
                var (modules, trueBranch, falseBranch) = _executionList[_currentIndex];
                var results = await Task.WhenAll(modules.Select(m => m.ExecuteAsync()));
                bool allTrue = results.All(r => r);
                MyFunc.AddMessage($"步骤 {_currentIndex + 1} 执行结果：{allTrue}");
                if (allTrue)
                {
                    var targetIndex = GetTargetIndex(trueBranch);
                    if (targetIndex >= 0)
                    {
                        _currentIndex = targetIndex;
                    }
                    else
                    {
                        _currentIndex++;
                    }
                }
                else
                {
                    var targetIndex = GetTargetIndex(falseBranch);
                    if (targetIndex >= 0)
                    {
                        _currentIndex = targetIndex;
                    }
                    else
                    {
                        _currentIndex++;
                    }
                }

                if (_isPaused)
                {
                    while (_isPaused && !token.IsCancellationRequested)
                    {
                        await Task.Delay(100, token);
                    }
                }
            }

            _isRunning = false;
            NotifyStateChanged();
        }

        private int GetTargetIndex(ObservableCollection<EditableItem> branch)
        {
            var selectedItem = branch.FirstOrDefault();
            if (selectedItem != null && int.TryParse(selectedItem.Content, out int targetIndex))
            {
                return targetIndex - 1;
            }
            return -1;
        }

        public void PauseExecution()
        {
            _isPaused = true;
            NotifyStateChanged();
        }

        public void ResumeExecution()
        {
            _isPaused = false;
            NotifyStateChanged();
        }

        public void StopExecution()
        {
            _isRunning = false;
            _isPaused = false;
            _currentIndex = 0;
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = null;
            NotifyStateChanged();
        }

        private void NotifyStateChanged()
        {
            StateChanged?.Invoke();
        }
    }
}